<template>
	<!-- 虚拟 -->
	<view style="width: 100vw;height: 100vh;background-color: #fff;">
		
		<!-- 头部搜索 与其余信息 -->
		<view style="height: 188rpx;width: 100vw;" class="chxy-column">
			<view style="height: 88rpx; ">
				<!-- :autoBack="autoBack" :titleStyle='navTitleStyle' :leftIcon='leftIcon' -->
				<up-navbar :autoBack="true">
					<template #center>
						<view> 
						<!-- @change="searchChange" -->
							<up-search @clickIcon="searchChange" @search="searchChange"  actionText="" searchIcon='https://oss.jtmckj.com/supplyH5/search-icon.png' :clearabled="false" placeholder="请输入" v-model="searchGoods" >
							</up-search>
						</view>
					</template>
				</up-navbar>
			</view>
			<view style="height: 100rpx;padding:  0 24rpx;">
				<view style="height: 30rpx;"></view>
				<view class="chxy-row-bt">
					<view style="font-family: PingFang SC;font-weight: bold;font-size: 32rpx;color: #212121;">{{storeUserInfo.orgName || ''}}</view>
					<view style="font-family: PingFang SC;font-weight: 500;font-size: 28rpx;color: #999999;">桌号 {{storeTableInfo.name || ''}}</view>
				</view>
			</view>
		</view>
		<view class="chxy-row">
			
			<!-- 左侧分类列表 -->
			<view style="width: 160rpx;overflow-y: scroll;border-radius: 0rpx 16rpx 0px 0rpx;" class="h100 ">
				<view v-for="(item,index) in leftList" :key="item.id" :id="index" :ref="item.id" @click="toAssign(item,index)" :class="leftCheckIndex === index ? 'checkBac': 'noCheckBac'">
					<up-image v-if="item.goodsTypeImage" width="66rpx" height="66rpx" :src="item.goodsTypeImage"></up-image>
					<up-image v-else width="66rpx" height="66rpx" src="https://jtmc.oss-cn-hangzhou.aliyuncs.com/h5-uniapp/h5-order/cart.png"></up-image>
					
					<view style="height: 10rpx;"></view>
					<view style="font-size: 20rpx;">{{item.name}}</view> 
				</view>
				<view >
					<view style="height: 120rpx;"></view>
				</view> 
			</view>
			
			<!-- 右侧商品列表 @refresher="refresher" @scrolltoupper="scrolltoupper" -->
			<jp-virtual-list code="id" class="h100" :refresher="true" isBackTop :data="listx" ref="search" @viewToView="viewToView">
				<template v-slot="{ list }">
					<view v-for="(item,index) in list" :key="item.id" :id="item.id" :ref="item.id">
						<view class="right-item" :style="'height:' + item.height +'rpx'" style="width: calc(100vw - 160rpx - 48rpx); margin-left: 20rpx;overflow: hidden;">
							<view v-if="item.title" class="right-item-title " style="height: 80rpx;background-color: #f5f5f5;">
								<view style="padding-top: 30rpx;color: #666666;font-size: 24rpx;margin-left: 20rpx;" >
									{{item.title}}
								</view>
							</view>
							<view class="chxy-row-ac" style="height: 238rpx;">
								
								<up-image v-if="item.attachment" width="200rpx" height="200rpx" :src="item.attachment" mode="aspectFill" radius='10rpx'></up-image>
								<up-image v-else width="200rpx" height="200rpx" src="https://jtmc.oss-cn-hangzhou.aliyuncs.com/h5-uniapp/h5-order/cart.png"></up-image>
								<view class="chxy-column-c-c" style="margin-left: 30rpx;width:316rpx; ">
									<view style="height: 40rpx;"></view>
									<view style="color: #212121;font-weight: bold;width: 310rpx;" class="over-hidden-two">{{item.name}}</view>
									<view style="margin: 18rpx 0;">星际会员{{item.vipPrice}}</view>
									<!-- 单品 -->
									<view v-if="item.type === '1' &&  item.priceList.length <= 1 && !item.goodsFlavor" class="chxy-row-bt" style="width: 100%; ">
										<view style="width: 130rpx;overflow-x: hidden;">{{item.salePrice}}</view> 
										<view><order-number-box @change="valChange($event,item,index,list)" :max="9999999" :min="0" v-model="item.qty" /></view>
									</view>
									<!-- 规格 -->
									<view v-if="item.type === '1' && item.priceList.length > 1 || item.goodsFlavor " class="chxy-row-bt" style="width: 100%; ">
										<view style="width: 130rpx;overflow-x: hidden;">{{item.salePrice}}</view> 
										<view @tap="$u.throttle(btnGgClick(item,index), 500)" style="position: relative;width: 88rpx;height: 48rpx;background: #212121;border-radius: 24rpx;border-radius: 24rpx;line-height:48rpx;text-align: center;color: #fff;font-size: 20rpx;">
											选规格
											<view style="position: absolute;top: -20rpx;right: 0;color: red;">
												<up-badge bgColor='red' :value="item.qty"></up-badge>
											</view>
										</view>
									</view>
									<!-- 套餐 -->
									<view v-if="item.type === '2'" class="chxy-row-bt" style="width: 100%; ">
										<view style="width: 130rpx;overflow-x: hidden;">{{item.salePrice}}</view> 
										<view @tap="$u.throttle(btnTcClick(item,index), 500)" style="position: relative;width: 88rpx;height: 48rpx;background: #212121;border-radius: 24rpx;border-radius: 24rpx;line-height:48rpx;text-align: center;color: #fff;font-size: 20rpx">
											选套餐
											<view style="position: absolute;top: -20rpx;right: 0;color: red;"> 
												<up-badge bgColor='red' :value="item.qty"></up-badge>
											</view>
										</view>
									</view>
									
									<view style="height: 30rpx;"></view>
								</view>
							</view>
							<view style="height: 2rpx;background : #F2F2F2;"></view>
							<!-- border-bottom: 1rpx solid #F2F2F2; -->
						</view>
					</view>
					<view >
						<view style="height: 120rpx;"></view>
					</view>
				</template>
			</jp-virtual-list>
		</view> 
		
		<!-- 购物车栏  -->
		<good-cart-nav ref="goodsCartNav" @goodsItemChange="goodsItemChange" @updat:zIndexNum="zIndexNum = $event" :zIndexNum='zIndexNum'></good-cart-nav> 
		
	    <!-- 已点订单 悬浮拖拽按钮 -->
		<movable-order></movable-order>   
		
		<!-- 套餐  -->
		<package-product ref="testProduct" :producModal="producModal" @update:show="showProduct = $event" @add="handleAddToCart" :show='showProduct'/>
		
		<!-- 规格 -->
		<package-specs ref="specsRef" @updateSpecsData='updateSpecsData'/>
		
	</view>
</template>
<script setup>
	import { ref, reactive, onMounted, nextTick } from 'vue'; 
	import { onLoad, onUnload,  onShow, onHide } from '@dcloudio/uni-app';
	import {  HFiveAppObjProcess, HFiveMemberAppObjProcess } from '@/api/public.js'
	import { initTableInfo,initTableInfoFinish,updateTableInfo } from "@/until/tools.js"
	import { useCartStore } from '@/store/cart.js';
	import { useTableStore } from '@/store/table.js';
	import { useUserStore } from '@/store/user.js';
	const storeCart = useCartStore();  // 购物车store 
	const storeUser = useUserStore(); 
	const storeTable = useTableStore(); 
	const storeUserInfo = ref({}) 
	const storeTableInfo = ref({})   
	
	// 商品
	const goodsCartNav = ref(null) // 购物车ref
	const timer = ref(null) // 定时器
	const search = ref() // 头部搜索关键字
	const leftCheckIndex = ref(0) // 左侧分类选中坐标
	const leftList = ref([])  // 左侧分类
	const isLeftClick = ref(false) // 左侧选中开关
	const listx = ref([]) // 商品数据
	const distanceList = ref([])  // 计算商品的总高度
	const listxCopy = ref([]) // 商品数据备份
	const leftListCopy = ref([]) // 商品分类数据备份
	
	// 套餐
	const zIndexNum = ref(1) // 当前套餐弹窗与购物车弹窗不同层级切换
	const showProduct = ref(false) // 当前套餐弹窗开关
	const producModal = ref({}) // 当前套餐信息
	const testProduct = ref() // 当前套餐弹窗ref 
	
	// 规格
	const specsModal = ref({}) // 当前规格弹窗信息
	const specsRef = ref() // 当前规格弹窗ref  
 
	// 接口查询商品列表
	const searchGoods = ref('') 

	
	// 返回不触发
	onLoad(( ) => { 
		initData()
		// 接口获取数据 在onMounted赋值与过滤
		console.log('onLoad')
		// nextTick(() => { 
		// 	goodsCartNav.value.initDataNav()
		// })
	});
	
	// 返回触发
	onShow(() => {
	    console.log('onShow')   
		nextTick(() => {
			goodsCartNav.value.initDataNav()
		})
	}); 
	
	const initData = () => {
		initUserInfoFun()
		initTableInfoFun()  
	}
	
	// 
	const initUserInfoFun = () => {
		storeUserInfo.value = storeUser.GetUserInfo()
		console.log(' storeUser.GetUserInfo()：', storeUser.GetUserInfo())
	}
	
	// 
	const initTableInfoFun = () => {
		storeTableInfo.value = storeTable.GetTableInfo()
		console.log(storeTableInfo.value);
	}
	
	// // 选中Vip权益
	// const updateMinVipFlag = (checkFlag) => {
		
	// }
	
	
	// 返回不触发
	onBeforeMount(() => {
		console.log('onBeforeMount') 
	}) 
	
	// 返回不触发
	// ws通知: 商品跟新方式有2种,单个商品跟新与所有商品跟新
	onMounted(() => {  
		onMountedFun()  
	});
	
	const onMountedFun =   () => {
	    uni.showLoading({
	    	title: '加载中',
	    	mask: true
	    });
	    // filterData()
	    console.log('onMounted')  
	    let resType = []
	    let resGoods = []
	    let resultGoods = []
	    let modalType = {"functionName":"GetGoodsTypeOrg_H5","contentData":""}
	    HFiveMemberAppObjProcess(modalType).then(resType => {  
	    	resType = resType 
	    	let modalGoogs = {"functionName": "getGoodsInfoTerminal_H5", "contentData": {"terminalType":"2","currentTime":'',}}
	    	HFiveMemberAppObjProcess(modalGoogs).then(resGoods => { 
	    		// console.log('resType:',resType)
	    		// console.log('resGoods:',resGoods)  
	    		resType.forEach((item,index)=>{ 
	    			resGoods.forEach((subitem,subindex)=>{ 
	    				let listGs = subitem.goodsType.split(',')
	    				listGs.forEach((tItem,tindex)=>{ 
	    					if(item.goodsTypeCode === tItem){
	    						let newSubItem = {...subitem} 
	    						newSubItem['height'] = 240
	    						if(!item['id']){
	    							item['id'] = 'Item' + index + subindex + tindex 
	    							item['name'] = item.goodsTypeName  
	    							newSubItem['title'] = item.goodsTypeName 
	    							newSubItem['height'] = 320
	    						} 
	    						newSubItem['goodsType'] = tItem
	    						newSubItem['qty'] = 0
	    						newSubItem['id'] = 'Item' + index + subindex + tindex
	    						newSubItem['name'] =  subitem.goodsName 
	    						resultGoods.push(newSubItem)
	    					} 
	    				})  
	    		    })
	    		}) 
	    		// console.log('result-resType',resType) 
	    		// console.log('result',resultGoods)  
				
	    		leftList.value = resType.filter(item => item.id); //resType
	    		if(resultGoods.length <= 0){
	    			uni.showToast({ title: '商品数据有问题，请联系管理员！', icon: 'none' })   
	    			return
	    		} 
	    		listx.value = resultGoods  
	    		nextTick(() => {
	    			let allRpx = 0
	    			distanceList.value = [] 
	    			listx.value.forEach((item,index)=>{
	    				if(item.title){ 
	    					distanceList.value.push(allRpx)
	    					allRpx += 320 
	    				}else{
	    					allRpx += 240
	    				}
	    			})  
	    		})
	    		uni.hideLoading();
	    	})  
	    })  
	}
	
	// 跟新规格
	const updateSpecsData =  (value) => {
		// 
		console.log('specsModal.value updateSpecsData：',value)
		listx.value.forEach((item,index)=>{  
		    if(item.id === value.id){
				listx.value[index].qty = value.qty
				listx.value[index].specsOthList = value.specsOthList
			} 
		}) 
		storeCart.SetCartList(listx.value)   
		nextTick(() => {  
			goodsCartNav.value.toRefresh()
		}) 
	}
	
	// 
	const filterData = async( ) => {
		const modalType = {"functionName":"GetGoodsTypeOrg_H5","contentData":""}
		const resType  = await HFiveMemberAppObjProcess(modalType)
		const modalGoogs = {"functionName": "getGoodsInfoTerminal_H5", "contentData": {"terminalType":"2","currentTime":''}}
		const resGoods  = await HFiveMemberAppObjProcess(modalGoogs) 
		const resultGoods = resType.flatMap(item =>
		    resGoods.filter(subitem => subitem.goodsType.split(',').includes(item.goodsTypeCode))
		        .map(subitem => ({ ...subitem, goodsType: item.goodsTypeCode }))
		);
		console.log('resultGoods',resultGoods) 
	}
	
	//  async
	const valChange =  (qty, goodItem, index,listx) => {   
		storeCart.SetCartList(listx)  
		nextTick(() => {  
			goodsCartNav.value.toRefresh()
		})
	}
	
	// 套餐跟新
	const packUpdate =  (recModal) => {
		console.log('packUpdate-recModal1：',recModal)
		// listx.value[0].qty = 9
		listx.value.forEach((item,index)=>{
			if(recModal.goodsCode === item.goodsCode){
				listx.value[index] = recModal
			}
		})
		console.log('packUpdate-recModal2：',listx.value)
		storeCart.SetCartList(listx.value)   
		nextTick(() => {  
			goodsCartNav.value.toRefresh()
		})
	}
	
	// 
	const goodsItemChange =  (value) => { 
		wsRefresherItem(value)
	}
	
	// 下拉刷新 - 或者跟新数据
	const wsRefresherItem = (value) => {
		console.log('wsRefresherItem...',value)   
		
		// 跟新单个
		let data = [...listx.value] 
		data.forEach((item)=>{
			
			if(item.id === value.id){
				console.log('item.id:',item.id)
				console.log('value.qty:',value.qty)
				item.qty = value.qty
			}
		}) 
		nextTick(() => { 
			listx.value = data  
			search.value.refreshers()  
		})               
	} 
	
	// 规格弹窗
	const btnGgClick =  (goodItem, index) => {
		console.log('btnGgClickgoodItem,index:', goodItem, index)
		nextTick(() => {
			specsRef.value.initDataSpecs(goodItem) 
		}) 
	}
	
	// 过滤数据
	const filterChaosData =  (val) => {
		let newList = JSON.parse(val) 
		// console.log('subitem.goodsFlavor未调整前：',newList[0].FlavorStr) 
		newList.forEach((bigitem,bigindex)=>{ 
			bigitem.FlavorStr = bigitem.FlavorStr.split(',');
			bigitem['defCheck'] = []
			bigitem.FlavorStr.forEach((item,index)=>{
			    if(item.includes('#')){
				    item = item.replace('#', '');
				    bigitem['defCheck'].push(item) 
				    bigitem.FlavorStr[index] = item
			    }
		    })
		})
		return newList
		
		// 单
		// newList[0].FlavorStr = newList[0].FlavorStr.split(',');  
		// newList[0].FlavorStr.forEach((item,index)=>{
		// 	if(item.includes('#')){
		// 		item = item.replace('#', '');
		// 		newList[0]['default'] = item 
		// 		newList[0].FlavorStr[index] = item
		// 	}
		// })
		// return newList[0]
	} 
	
	const handleAddToCart =  ( recModal ) => {
		showProduct.value = false
		console.log('recModal：',recModal)
		packUpdate(recModal)
	}
	
	// 套餐
	const btnTcClick =  (goodItem, index) => {
		console.log('btnTcClick',goodItem, index) 
		goodItem?.priceList.forEach((item)=>{
			item?.detail.forEach((subitem)=>{
				if(subitem.operType === '0' && subitem.choiceType === '1'){
					subitem?.goodsDetail.forEach((vitem)=>{ 
						// 特殊的套餐结构需要补充选中状态，其余类型无需 vitem['check'] = false 
					    vitem['check'] = false 
						// goodsFlavor 调整成正常数据结构 并通过 vitem.goodsFlavor.Name 判断是否已经过滤完
						if(vitem.goodsFlavor && !vitem?.goodsFlavor[0]?.Name){
							console.log('vitem.goodsFlavor...1123')
							vitem.goodsFlavor =  filterChaosData(vitem.goodsFlavor)
							console.log('最后1：',vitem.goodsFlavor)
						} 
					})
				}else{
					subitem?.goodsDetail.forEach((vitem)=>{ 
						vitem.defaultQty = Number(vitem.defaultQty) // 此处可以将默认值赋值为0 作为伪清空
						// goodsFlavor 调整成正常数据结构 并通过 vitem.goodsFlavor.Name 判断是否已经过滤完
						if(vitem.goodsFlavor && !vitem?.goodsFlavor[0]?.Name){
							console.log('vitem.goodsFlavor...',vitem.goodsFlavor)
							vitem.goodsFlavor =  filterChaosData(vitem.goodsFlavor) 
							console.log('最后2：',vitem.goodsFlavor)
						} 
					})
				} 
				
			})
		})
		zIndexNum.value = 1
		showProduct.value = true 
		producModal.value = goodItem  
		nextTick(() => { 
			testProduct.value.initDataProduct() 
		}) 
		
	} 
	
	const tt = ( ) => { 
		console.log('test...tt')
	}
	// 去开通
	const test = ( ) => {
		// 先弹出确认框
		console.log('test...')
		wsRefresher()
		// wsScrolltoupper()
	} 
    
	//  @change="searchChange"实时触发  >>> searchChange按钮确定触发
	const searchChange = () => { 
		// 未处理
	} 

    // 通过id 定位位置
	const toAssign = (item, index) => {
		isLeftClick.value = true
		leftCheckIndex.value = index
		nextTick(() => {
			console.log('item',item)
			search.value.toAssign(item.id, '')
		})
		
		
	}
	// const toAssign = ( ) => { 
	// 	// this.$refs.search.toAssign('Item999', this)
	// }
	
	// 尾巴补数据 addPage(data)  距顶部/左边多远时（单位px），滚动到顶部触发 scrolltoupper 事件
	const wsScrolltoupper = () => {
		console.log('wsScrolltoupper...')
		const data = []
		for (let i = 0; i < 40; i++) {
			data.push({
				name: `Item${i}`,
				index: i,
				id: `Item${i}`,
				title: (i % 5 === 0 || i === 0) ? ('跟新==标题除以5加1：' + (i)  ) : '',
				height: (i % 5 === 0 || i === 0) ? 320 : 240, //(Math.floor(Math.random() * 100)+200),
				children: []
			})
		}
		nextTick(() => { 
			let allRpx = 0 // 此处应该是之前的最大高度
			data.forEach((item,index)=>{
				if(item.title){ 
					distanceList.value.push(allRpx)
					allRpx += 320 
				}else{
					allRpx += 240
				}
			}) 
			// 告诉组件刷新成功了
			search.value.addPage(data) 
		}) 
	}
	// 下拉刷新 - 或者跟新数据
	const wsRefresher = ( ) => {
		console.log('wsRefresher...')   
		
		// 跟新单个
		const data = [...listx.value] 
		data[0].title = 'adfasdfas'  
		data[5].title = '33355adfasdfas'  
		data[15].title = '1533355adfasdfas'  
		data[20].title = '2033355adfasdfas'  
		nextTick(() => { 
			listx.value = data 
			search.value.refreshers()  
		})
		
		// 跟新全部
		// uni.showLoading({
		// 	title:  '正在加载',
		// 	mask:  false
		// });
		// const data = []
		// for (let i = 0; i < 39; i++) {
		// 	data.push({
		// 		name: `Item${i}`,
		// 		index: i,
		// 		id: `Item${i}`,
		// 		title: (i % 5 === 0 || i === 0) ? ('跟新 ！！！ 除以5加1：' + (i)  ) : '',
		// 		height: (i % 5 === 0 || i === 0) ? 320 : 240, //(Math.floor(Math.random() * 100)+200),
		// 		children: []
		// 	})
		// }
		// nextTick(() => {
			
		// 	let allRpx = 0
		// 	distanceList.value = [] 
		// 	data.forEach((item,index)=>{
		// 		if(item.title){ 
		// 			distanceList.value.push(allRpx)
		// 			allRpx += 320 
		// 		}else{
		// 			allRpx += 240
		// 		}
		// 	})
		// 	 listx.value = data
		// 	    // 告诉组件刷新成功了
		// 		search.value.refreshers() 
		// 		// search.value.toAssign("Item0", '')
		// 		uni.hideLoading();  
		// })
		                
	} 
	// 左侧位置 leftCheckIndex.value 赋值选中
	const viewToView = (e) => {
		// console.log('viewToView...',isLeftClick.value)
		// console.log('viewToViewe：', e.detail.scrollTop / (uni.upx2px(100) / 100))
		if (isLeftClick.value) {
			isLeftClick.value = false
			return
		}
		// 防抖
		if (timer.value) {
			clearTimeout(timer.value)
		}
		timer.value = setTimeout(() => {  
			let scrollTop = e.detail.scrollTop / (uni.upx2px(100) / 100) //滚动的高度 
			let linshi = 0
			// console.log('this.distanceLisindex1:', scrollTop)
			// console.log('this.distanceLisindex2:', distanceList.value) 
			distanceList.value.forEach((item,index)=>{
				if(scrollTop > item){
					linshi = index
				} 
			}) 
			// console.log('this.distanceLisindex3:', linshi) 
			if (linshi < -1) return  
			leftCheckIndex.value = linshi  
		}, 500)
	}
</script>

<style lang="scss" scoped>
	.h100 {
		height: calc(100vh - 188rpx);
	}

	.list_item {
		display: flex;
		justify-content: center;
		align-items: center;
		border: 1px solid #f5f5f5;
	}

	.noCheckBac {
		background-color: #F5F5F5;
		height: 144rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.checkBac {
		background: linear-gradient(to right, #c1c1c1, #f3f3f3);
		height: 144rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		border-left: 10rpx solid #666666;
		
	}
</style>